const express = require('express')
const router = express.Router()
const articleService = require('services/article')
const settingService = require('services/setting')

router.get('/', async (req, res, next) => {
  try {
    let result = await articleService.search(req.query)
    res.json(result)
  } catch (e) {
    next(e)
  }
})

router.get('/categories', async (req, res, next) => {
  try {
    let categories = await settingService.get('ArticleCategorieOptions')
    res.json(categories ? categories.split(',') : [])
  } catch (e) {
    next(e)
  }
})

router.get('/:id', async (req, res, next) => {
  try {
    let article = await articleService.get(req.params.id)
    res.json(article)
  } catch (e) {
    next(e)
  }
})

router.delete('/:id', async (req, res, next) => {
  try {
    await articleService.remove(req.params.id)
    res.json({ status: "ok" })
  } catch (e) {
    next(e)
  }
})

router.post('/', async (req, res, next) => {
  try {
    const article = await articleService.create(req.body)
    res.json(article)
  } catch (e) {
    next(e)
  }
})

router.put('/:id', async (req, res, next) => {
  try {
    const { title, content, category } = req.body
    let article = await articleService.save(req.params.id, {
      title,
      content,
      category
    })
    res.json({
      status: 'ok'
    })
  } catch (e) {
    next(e)
  }
})

module.exports = router